<?php

namespace app\api\controller;

use app\admin\model\Agentarea;
use app\admin\model\Contract;
use app\admin\model\Guige;
use app\admin\model\Notice;
use app\admin\model\Otherconfig;
use app\admin\model\Order;
use app\admin\model\Search;
use app\admin\model\Unit;
use app\common\controller\Api;
use app\admin\model\Ticket;
use app\admin\model\Type;
use app\admin\model\Detail;
use EasyWeChat\Factory;
use think\Db;


/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 水票
     * Summary of ticket
     * @param mixed $page
     * @return void
     */
    public function area()
    {
        $areas = Db::name('area')->where(['id' => 37])->field('id,pid,level,name')->select();//省
        $children = Db::name('area')->where(['id' => 104])->field('id,pid,level,name')->select();//市
        $secondChildren = Db::name('area')->where(['pid' => 104])->field('id,pid,level,name')->select();//市
        foreach ($children as $key => $value) {
            $children[$key]['children'] =  $secondChildren;
        }
        foreach($areas as $key => $value) {
          
            $areas[$key]['children'] =  $children;
        }
        $this->success('suc',['UserDistrict' =>$areas ]);
        $areas = Db::name('area')->field('id,pid,level,name')->select();

        // 构建节点映射，便于按 pid 组装父子关系
        $nodes = [];
        foreach ($areas as $row) {
           
                    $id = $row['id'];
                    $nodes[$id] = [
                        'id' => $id,
                        'pid' => $row['pid'] ?? 0,
                        'name' => $row['name'] ?? '',
                        'level' => (string)($row['level'] ?? '1'),
                        'children' => [],
                    ];
           
           
        }
        
        // 组装树：将子节点挂到其父节点的 children 下；收集根节点
        $roots = [];
        

        foreach ($nodes as $id => &$node) {
            $pid = $node['pid'];
            if (!empty($pid) && isset($nodes[$pid])) {
                $nodes[$pid]['children'][] = &$node;
            } else {
                $roots[] = &$node;
            }
        }
        unset($node);
       
        $list = self::formatTree($roots);

        $this->success('suc', ['UserDistrict' => $list]);

    }
    public static function formatTree($treeData)
    {
        $result = [];
        foreach ($treeData as $item) {
            $formatted = [
                'name' => $item['name'] ?? '',
                'level' => (string)($item['level'] ?? '1'),
            ];

            if (!empty($item['children'])) {
                $formatted['children'] = self::formatTree($item['children']);
            }

            $result[] = $formatted;
        }
        return $result;
    }
    public function contract()
    {
        $this->success('suc',Contract::select());
    }
     
    public function ticket()
    {   
        $where['status'] = 1;
        $advice = $this->request->get('advice',0);
        if($advice == 1) {
            $where['commended'] = 1;
        }
        $page = $this->request->get('page',1);
        $list = Ticket::where($where)->paginate(20,false,['page' => $page])->each(function(&$item){
            $item['image'] = $this->request->domain().$item['image'];
        });
        $this->success('suc',$list);
    }
    public function TicketDetail($id)
    {
        $detail = Ticket::find($id);
        $detail['image'] = $this->request->domain().$detail['image'];
        $this->success('suc',$detail);
    }
    public function productDetail($id)
    {
        $detail = Detail::find($id);
        if($detail['images']) {
            $images = explode(',',$detail['images']);
           
            foreach($images as &$value) {
                $value = $this->request->domain().$value;
            }
            $detail['images'] =  $images;
          
        }
        $detail['type_name'] = Type::find($detail['type_id'])['name'];
        $detail['guige_name'] = Guige::find($detail['guige_id'])['guige'];
        $this->success('suc', $detail);
    }
    /**
     * 类型
     * Summary of type
     * @return void
     */
    public function type()
    {
        $list = Type::where(['status' => 1])->select();
        $this->success('suc',$list);
    }
    public function specification($typeId = '')
    {
        $list = Guige::where(['type_id' => $typeId,'status' => 1])->select();
        foreach($list as $key=> $value ) {
            $list[$key]['detailId'] = '';
            $tmp =  Detail::where(['type_id' =>$typeId, 'guige_id' => $value['id']])->field('id,active,active_money')->find();
            
           if($tmp) {
                $list[$key]['detailId'] = $tmp['id'];
                if($tmp['active'] == 1) {//如果是活动商品
                    $list[$key]['money'] = $tmp['active_money'];
                }
                $list[$key]['active'] = $tmp['active'];
                $unitDetail = Unit::find($value['unit']); 
                $list[$key]['guige'] =  $list[$key]['guige']. $unitDetail['unit'];
           } else {
              unset($list[$key]);
           }
         

          
        }
        $this->success(  $list);
    }
    public function list()
    {
       $advice = $this->request->get('advice',0);#类型，0是通过类型访问，必须加上typeId，参数，1是推荐,2是活动（用于抽奖 的）
       $typeId = $this->request->get('typeId',0);
       $page = $this->request->get('page',1);
       $search = $this->request->get('search','');
       $where['status'] = 1;
       if(empty($search)) {
            if($advice == 0) {
                if(empty($typeId)) {
                $this->error('非法请求');
                }
                $where['type_id'] = $typeId;
            } else if($advice == 1) {
            $where['commend'] = 1;
            } else {
            $where['active'] = 1;
            }
       }
       if($search) {
            unset($where);
            $where['name'] = ['like',"%$search%"];
            Db::name('search_record')->insert(['name' => $search,'create_time' => time()]);
            $list = Search::where(['name' => $search])->find();
            if($list) {//如果有
                $list->num += 1;
                $list->save();
            }else {
                Search::insert(['name' =>  $search,'num' => 1]);
            }
       }
     
       $list = Detail::where( $where)->paginate(20,false,['page' => $page])->each(function($item) {
            $images = explode(',',$item['images']);
            foreach($images as &$value) {
                $value = $this->request->domain().$value;
            }
            $item['images'] =  $images;
       });
       $this->success('suc',$list);
    }
    public function banner()
    {
        $list = Db::name('banner')->where('status',1)->select();
        foreach ($list as $key => &$value) {
            $value['image'] = $this->request->domain().$value['image'];
        }
        $this->success('suc',$list);
    }
    public function policy($status = 0)
    {
        if(!in_array($status,[0,1,2,3])) {
            $status = 0;
        }
        $list = Db::name('policy')->where('status',$status)->select();
      
        $this->success('suc',$list);
    }
    //自动取消订单
    public function autoSetCancle()
    {
       Order::where(['status' => 0])->where('create_time','<',time()- 30 * 60)->update(['status' => 7]);
      
    }
    public function search()
    {
        $list = Search::order('num desc')->limit(20)->select();
        $this->success('suc',$list);
    }

    public function notice()
    {
        $list = Notice::where(['status' => 2])->select();
        $this->success('suc',$list);
    }
    public function agentArea()
    {
        $list = Agentarea::select();
        $this->success('suc',$list);
    }
    public function noticeUser()
    {
        $siteConfig = Otherconfig::find(1);
      
        $config = [
            'app_id' => $siteConfig['app_id'],
            'secret' =>  $siteConfig['secret']
        ];
        $app = Factory::miniProgram($config);
        // try{
            $result = $app->subscribe_message->send([
                'touser' =>  'oEJhv1z-iLVCwsFxIJuKYd-gwdPs' ,
                'template_id' => '3m5WnTYt3E-07Y3gqMydPsl3zaPse2gnao4WEHq6WjY',
                'page' => '',
                'data' => [
                    'character_string4' => ['value' => date('YmdHis')],
                    'thing3' => ['value' => '商品名称'],
                    'thing8' => ['value' => '订单信息'],
                    'phrase14' => ['value' => '已送达']
                ],
            ]);
            $this->success('suc',$result);
        // }catch(\Exception $e){
        //    $this->error($e->getFile().$e->getLine().$e->getMessage());
        // }
       
    } 
    
}
